from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import db
from info.models import News, User, Comment
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import news_blue


@news_blue.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():

    # 是否登陆校验
    if not g.user:
        return jsonify(errno=RET.NODATA, errmsg='用户不存在')

    # 1 获取参数
    news_id = request.json.get('news_id')
    content = request.json.get('comment')
    parent_id = request.json.get('parent_id')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻查询失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    # 2 校验参数
    if not all([news_id,content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    # 3 数据入库
    comment = Comment()
    comment.user_id = g.user.id
    comment.news_id = news_id
    comment.content = content
    comment.parent_id = parent_id

    db.session.add(comment)
    db.session.commit()

    # 4 返回响应
    return jsonify(errno=RET.OK, errmsg='评论成功')


@news_blue.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():

    # 0 验证用户是否登陆
    if not g.user:
        return jsonify(errno=RET.NODATA,errmsg='用户未登录')

    # 1获取参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')


    # 2 校验参数
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='查询新闻失败')

    if not news:
        return jsonify(errno=RET.PARAMERR, errmsg='新闻不存在')

    if action not in ['collect','cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg='操作类型有错误')


    # 3 数据入库
    if action == 'collect':
        if news not in g.user.collection_news:
            g.user.collection_news.append(news)
    if action == 'cancel_collect':
        if news in g.user.collection_news:
            g.user.collection_news.remove(news)


    # 4 返回响应
    return jsonify(errno=RET.OK,errmsg='收藏或取消收藏成功')


@news_blue.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):

    # user_id = session.get('user_id')
    # user = ''
    # if user_id:
    #     user = User.query.get(user_id)
    # 根据新闻编号获取新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='新闻对象查询失败')
    # 判断新闻是否存在
    if not news:
        abort(404)

    is_collected = False
    if g.user and news in g.user.collection_news:
        is_collected = True

    # 查询评论
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='评论查询失败')

    # 将评论对象列表转换为字典列表
    comments_list = []
    for comment in comments:
        comments_list.append(comment.to_dict())


    # 把新闻对象转化为字典数据
    data ={
        'news_info': news.to_dict(),
        'user_info': g.user.to_dict() if g.user else '',
        'is_collected': is_collected,
        'comments_list':comments_list
    }
    # 携带数据,渲染新闻详情页面
    return render_template('news/detail.html',data=data)
